<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\wh\admin;

use app\wh\builder\Admin;
use app\wh\builder\ZBuilder;
use app\user\model\UserGroup as UserGroupModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Give as GiveModel;
use app\user\model\User as UserModel;
use think\Db;

/**
 * 统计管理控制器
 * @package app\admin\controller
 */
class Stat extends Admin
{

    /**
     * 首页统计
     */
    public function ajaxIndex()
    {

        $starttime = strtotime(date("Y-m-d", (time())));
        $endtime = strtotime(date("Y-m-d 23:59:59", time()));

        //所有客户
        $kh = Db::name('mill_client')->count();
        //所有订单
        $dd = Db::name('mill_order')->count();
        //本年度生产汇总
        $starttime_year = mktime(0,0,0,1,1,date('Y'));
        $endtime_year = strtotime('+1 year',$starttime) - 1;
        $je1 = Db::name('mill_order_archives_give')
            ->alias('g')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where("g.status1_time between {$starttime_year} and {$endtime_year}")
            ->sum('a.one_area');
        $je1 = round($je1).'m²';
        $je2 = Db::name('mill_order_archives_give')
            ->alias('g')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where("g.status2_time between {$starttime_year} and {$endtime_year}")
            ->sum('a.one_area');
        $je2 = round($je2).'m²';
        $je3 = Db::name('mill_order_archives_give')
            ->alias('g')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where("g.status3_time between {$starttime_year} and {$endtime_year}")
            ->sum('a.one_area');
        $je3 = round($je3).'m²';
        $je4 = Db::name('mill_order_archives_give')
            ->alias('g')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where("g.status4_time between {$starttime_year} and {$endtime_year}")
            ->sum('a.one_area');
        $je4 = round($je4).'m²';
        $je = "<span>开料：{$je1}</span>&nbsp;&nbsp;<span>钣金：{$je2}</span><br><span>喷涂：{$je3}</span>&nbsp;&nbsp;<span>发货：{$je4}</span>";
        //今日新增客户
        $xs = Db::name('mill_client')->where("create_time between {$starttime} and {$endtime}")->count();

        echo json_encode(array('kh' => $kh,'dd' => $dd,'je'=>$je,'xs'=>$xs));
    }

    /**
     * 订单阶段统计
     */
    public function ajaxOrderStatus()
    {
        //车间类型
        $mill_id = input('mill_id');
        //时间段 year:年 month:月 day:日
        $date = input('date');
        $series_type = input('series_type','line');
        $series_name = input('series_name','');
        //默认今天
        //$starttime = strtotime(date("Y-m-d", (time()-6*86400)));
        $starttime = strtotime(date("Y-m-d", (time())));
        $endtime = strtotime(date("Y-m-d 23:59:59", time()));

        if($date == 'year'){
            //本年
            $starttime = mktime(0,0,0,1,1,date('Y'));
            $endtime = strtotime('+1 year',$starttime) - 1;
        }
        elseif($date == 'month'){
            //本月
            $starttime = mktime(0,0,0,date('m'),1,date('Y'));
            $endtime = strtotime('+1 month',$starttime) - 1;
        }
        elseif($date == 'day'){
            //本日
            $starttime = strtotime(date('Y-m-d'));
            $endtime = strtotime('+1 day',$starttime) - 1;
        }

        $time_input = input('time');
        if(!empty($time_input)){
            $time_input = explode(' - ',$time_input);
            $starttime = strtotime($time_input[0]);
            $endtime = strtotime(date("Y-m-d 23:59:59", strtotime($time_input[1])));
        }

        $day = intval(($endtime+1-$starttime)/86400);

        $date = date('Y-m-d', $starttime);
        $end_date = date('Y-m-d 23:59:59', $endtime);

        //车间类型
        $status_where2 = "1";
        if($mill_id == 1){
            $user_ids = Db::name('admin_user')->where([['mill_id','<>',1]])->column('id');
            if(!empty($user_ids)){
                foreach ($user_ids as $uid){
                    $status_where2 .= " and g.status_flow not like '%|{$uid}\\_%' ";
                }
                $status_where2 = trim($status_where2,'and');
            }
            else $status_where2 .= " and 1<>1";
        }
        else if($mill_id == 2){
            $user_ids = Db::name('admin_user')->where(['mill_id'=>2])->column('id');
            if(!empty($user_ids)){
                $status_where2 .= " and (";
                foreach ($user_ids as $uid){
                    $status_where2 .= " g.status_flow like '%|{$uid}\\_%' or";
                }
                $status_where2 = trim($status_where2,'or').")";
            }
            else $status_where2 .= " and 1<>1";
        }
        else if($mill_id == 3){
            $user_ids = Db::name('admin_user')->where(['mill_id'=>3])->column('id');
            if(!empty($user_ids)){
                $status_where2 .= " and (";
                foreach ($user_ids as $uid){
                    $status_where2 .= " g.status_flow like '%|{$uid}\\_%' or";
                }
                $status_where2 = trim($status_where2,'or').")";
            }
            else $status_where2 .= " and 1<>1";
        }

        //开料
        $status1_where[] = ['g.status_flow','like','%\\_1|%'];
        $status1_where[] = ['g.status1_time','between time',[$date,$end_date]];
        $status1 = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field('ceil(ifnull(sum(a.one_area),0)) as area_sum,count(g.id) as number_sum')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($status1_where)
            ->whereRaw($status_where2)
            ->find();

        //钣金
        $status2_where[] = ['g.status_flow','like','%\\_2|%'];
        $status2_where[] = ['g.status2_time','between time',[$date,$end_date]];
        $status2 = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field('ceil(ifnull(sum(a.one_area),0)) as area_sum,count(g.id) as number_sum')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($status2_where)
            ->whereRaw($status_where2)
            ->find();

        //喷涂
        $status3_where[] = ['g.status_flow','like','%\\_3|%'];
        $status3_where[] = ['g.status3_time','between time',[$date,$end_date]];
        $status3 = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field('ceil(ifnull(sum(a.one_area),0)) as area_sum,count(g.id) as number_sum')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($status3_where)
            ->whereRaw($status_where2)
            ->find();

        if($mill_id){

            exit(json_encode(array('status1' => $status1,'status2' => $status2,'status3' => $status3,'series_type' => $series_type, 'date' => date('Y-m-d',$starttime).' - '.date('Y-m-d',$endtime))));
        }

        //$value_name = '订单阶段';
        $value_title = ['开料', '钣金', '喷涂'];
        $legend_data = ['产品数量 个', '总面积 M²'];
        $value = [
            [
                'name'              =>  '产品数量 个',
                'type'              =>  $series_type,
                'smooth'            =>  true,
                'data'              =>  [
                    floatval($status1['number_sum']),
                    floatval($status2['number_sum']),
                    floatval($status3['number_sum']),
                ],
                'itemStyle'         =>  [
                    'normal'        =>  [
                        'label'     =>  [
                            'show'  =>  true
                        ]
                    ]
                ]
            ],
            [
                'name'              =>  '总面积 M²',
                'type'              =>  $series_type,
                'smooth'            =>  true,
                'data'              =>  [
                    floatval($status1['area_sum']),
                    floatval($status2['area_sum']),
                    floatval($status3['area_sum']),
                ],
                'itemStyle'         =>  [
                    'normal'        =>  [
                        'label'     =>  [
                            'show'  =>  true
                        ]
                    ]
                ]
            ],
        ];
        echo json_encode(array('legend_data' => $legend_data,'series_type' => $series_type,'series_name' => $series_name,'value_title' => $value_title,'value' => $value, 'date' => date('Y-m-d',$starttime).' - '.date('Y-m-d',$endtime)));
    }

    /**
     * 覆盖率统计
     */
    public function ajaxPaintCo()
    {

        //时间段 year:年 month:月 day:日
        $date = input('date');
        $series_type = input('series_type','line');
        $series_name = input('series_name','');
        //默认今天
        $starttime = strtotime(date("Y-m-d", (time())));
        $endtime = strtotime(date("Y-m-d 23:59:59", time()));

        if($date == 'year'){
            //本年
            $starttime = mktime(0,0,0,1,1,date('Y'));
            $endtime = strtotime('+1 year',$starttime) - 1;
        }
        elseif($date == 'month'){
            //本月
            $starttime = mktime(0,0,0,date('m'),1,date('Y'));
            $endtime = strtotime('+1 month',$starttime) - 1;
        }
        elseif($date == 'day'){
            //本日
            $starttime = strtotime(date('Y-m-d'));
            $endtime = strtotime('+1 day',$starttime) - 1;
        }

        $time_input = input('time');
        if(!empty($time_input)){
            $time_input = explode(' - ',$time_input);
            $starttime = strtotime($time_input[0]);
            $endtime = strtotime(date("Y-m-d 23:59:59", strtotime($time_input[1])));
        }

        $day = intval(($endtime+1-$starttime)/86400);

        $date = date('Y-m-d', $starttime);
        $end_date = date('Y-m-d 23:59:59', $endtime);

        //面积表总数,产品总数
        $archives_where[] = ['o.archives_sign_time','between time',[$date,$end_date]];
        $archives = Db::name('mill_order')
            ->alias('o')
            ->field('count(DISTINCT o.id) as order_sum,GROUP_CONCAT(DISTINCT o.id) as order_ids,ceil(ifnull(sum(a.number*a.one_area),0)) as row_area')
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->where($archives_where)
            ->find();

        //已完成面积,已完成数量
        $give_where[] = ['g.status','>=',3];
        $give_where[] = ['g.status3_time','between time',[$date,$end_date]];
        if(empty($archives['order_ids']))$give_where[] = ['g.order_id','=',0];
        else $give_where[] = ['g.order_id','in',$archives['order_ids']];
        $give = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field('ceil(ifnull(sum(a.one_area),0)) as area_sum,count(g.id) as number_sum')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($give_where)
            ->find();
        $give['no_area_sum'] = $archives['row_area'] - $give['area_sum'];
        if($give['no_area_sum'] <= 0)$give['no_area_sum'] = 0;

        $archives['order_sum'] = '84';
        $archives['row_area'] = '55';
        $value_title = [];
        $title = [
            [
                'subtext' =>  '最高覆盖率：54%    最低覆盖率：12%',
                'left'      =>  'center',
                'top'      =>  '85%',
                'subtextStyle'  =>  [
                    'color'  =>  "#000",
                    'fontSize' =>  '14',
                ],
            ],
        ];
        $legend_data = ['最高覆盖率','最低覆盖率',];
        $value = [
            [
                'name'    =>  '覆盖率',
                'type'    =>  $series_type,
                //'selectedMode'  =>  true,
                'radius'  =>  ['40%', '70%'],
                'center'  =>  ['35%', '50%'],
                'data'    =>  [
                    [
                        'name'      =>  '最高覆盖率',
                        'value'     =>  floatval($archives['order_sum']),
                    ],
                    [
                        'name'      =>  '最低覆盖率',
                        'value'     =>  floatval($archives['row_area']),
                        //'selected'     =>  true,
                    ],
                ],
                'roseType'  => 'radius',
                //'roseType'  => 'area',
                'label'    =>  [
                    'normal'        =>  [
                        'show'      =>  true,
                        'position'      =>  'center',
                        //'color'      =>  '#4c4a4a',
                        'formatter'      =>  '{total|50%}',
                        'rich'      =>  [
                            'total' =>  [
                                'fontFamily'  =>  "微软雅黑",
                                'fontSize'  =>  "24",
                                'color'  =>  "#000",
                            ],
                        ],
                    ],
                    'emphasis'        =>  [
                        'show'      =>  true,
                    ],
                ],
            ],
        ];
        echo json_encode(array('legend_data' => $legend_data,'series_type' => $series_type,'series_name' => $series_name,'title' => $title,'value_title' => $value_title,'value' => $value, 'date' => date('Y-m-d',$starttime).' - '.date('Y-m-d',$endtime)));
    }

    /**
     * 发货数据统计
     */
    public function ajaxOrderJe()
    {
        //时间段 year:年 month:月 day:日
        $date = input('date');
        $series_type = input('series_type','line');
        $series_name = input('series_name');
        //默认今天
        //$starttime = strtotime(date("Y-m-d", (time()-6*86400)));
        $starttime = strtotime(date("Y-m-d", (time())));
        $endtime = strtotime(date("Y-m-d 23:59:59", time()));
        //时间差
        $day_time = 0;

        if($date == 'year'){
            //本年
            $starttime = mktime(0,0,0,1,1,date('Y'));
            $endtime = strtotime('+1 year',$starttime) - 1;

            //时间差
            $day_time = abs(date('Y',$endtime+1)-date('Y',$starttime)) * 12 + abs(date('m',$endtime+1)-date('m',$starttime));

            //x轴单位
            $series_name = '年';
        }
        elseif($date == 'month'){
            //本月
            $starttime = mktime(0,0,0,date('m'),1,date('Y'));
            $endtime = strtotime('+1 month',$starttime) - 1;

            //时间差
            $day_time = intval(($endtime+1-$starttime)/86400);

            //x轴单位
            $series_name = '月';
        }
        elseif($date == 'day'){
            //本日
            $starttime = strtotime(date('Y-m-d'));
            $endtime = strtotime('+1 day',$starttime) - 1;

            //时间差
            $day_time = intval(($endtime+1-$starttime)/86400);

            //x轴单位
            $series_name = '日';
        }
        else{

            //时间差
            $day_time = intval(($endtime+1-$starttime)/86400);

            //x轴单位
            $series_name = '日';
        }

        $time_input = input('time');
        if(!empty($time_input)){
            $time_input = explode(' - ',$time_input);
            $starttime = strtotime($time_input[0]);
            $endtime = strtotime(date("Y-m-d 23:59:59", strtotime($time_input[1])));

            //时间筛选超过3年，按年算
            if(date('Y',$endtime+1)-date('Y',$starttime)>3){

                //时间差
                $day_time = date('Y',$endtime+1)-date('Y',$starttime);
                $date = 'year';
                //x轴单位
                $series_name = '年';
            }
            //时间筛选超过2个月，按月算
            elseif(abs(date('Y',$endtime+1)-date('Y',$starttime)) * 12 + abs(date('m',$endtime+1)-date('m',$starttime))>3){

                //时间差
                $day_time = abs(date('Y',$endtime+1)-date('Y',$starttime)) * 12 + abs(date('m',$endtime+1)-date('m',$starttime));
                $date = 'month';
                //x轴单位
                $series_name = '月';
            }
            else{
                //时间差
                $day_time = intval(($endtime+1-$starttime)/86400);
                $date = 'day';
                //x轴单位
                $series_name = '日';
            }

        }

        while (1 <= $day_time) {

            //年
            if($date == 'year'){

                $new_date = date('Y-m-01', strtotime("-{$day_time} month",strtotime(date('Y-m-01',($endtime + 1)))));
                $end_date = date('Y-m-d H:i:s',strtotime("+1 month",strtotime($new_date))-1);

                $date_title = date('Y年m月',strtotime($new_date));
            }
            //月
            elseif($date == 'month'){

                $new_date = date('Y-m-d', strtotime("-{$day_time} day",($endtime + 1)));
                $end_date = date('Y-m-d H:i:s',strtotime("+1 day",strtotime($new_date))-1);

                $date_title = date('m月d日',strtotime($new_date));
            }
            //日
            else{
                $new_date = date('Y-m-d', strtotime("-{$day_time} day",($endtime + 1)));
                $end_date = date('Y-m-d H:i:s',strtotime("+1 day",strtotime($new_date))-1);

                $date_title = date('m月d日',strtotime($new_date));
            }

            //条件
            $where = [
                ['g.status','=',4],
                ['g.status4_time','between time',[$new_date,$end_date]]
            ];
            $address = Db::name('mill_order_archives_give')
                ->alias('g')
                ->field('ceil(ifnull(sum(a.one_area),0)) as area_sum,count(g.id) as number_sum')
                ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                ->where($where)
                ->find();

            $address['number_sum'] = rand(100, 2000);
            $address['area_sum'] = rand(100, 2000);

            $transaction['num'][$date_title] = floatval($address['number_sum']);
            $transaction['area'][$date_title] = floatval($address['area_sum']);
            --$day_time;
        }

        $value_title = array_keys($transaction['num']);
        $legend_data = [];
        $value = [
            [
                'name'          =>  '数量',
                'type'          =>  $series_type,
                'smooth'        =>  true,
                'data'          =>  array_values($transaction['num']),
                'areaStyle'     =>  [
                    'color'     =>  '#e9ecff'
                ]
            ],
        ];
        echo json_encode(array('legend_data' => $legend_data,'series_type' => $series_type,'series_name' => $series_name,'value_title' => $value_title,'value' => $value, 'date' => date('Y-m-d',$starttime).' - '.date('Y-m-d',$endtime)));

    }

    /**
     * 生产线进度统计
     */
    public function speed($archives_status=1)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map2 = 'g.status > 0 and ';
        //默认日期：今天
        $times[0] = strtotime(date('Y-m-d'));
        $times[1] = strtotime(date('Y-m-d 23:59:59'));

        if(!empty($map)){
            $m_v_i = 0;
            foreach ($map as &$m_v){
                /*if(in_array('g.status_flow',$m_v) && !empty($m_v[2])){
                    $m_v[1] = 'like';
                    $m_v[2] = trim($m_v[2],'%');
                    $archives_status = trim($m_v[2],'%');
                    $m_v[2] = "%_".trim($m_v[2],'%')."|%";
                }*/
                //else $archives_status = 0;
                if (in_array('times',$m_v)){
                    $times[0] = strtotime($m_v[2][0]);
                    $times[1] = strtotime($m_v[2][1]);
                    unset($map[$m_v_i]);
                }

                $m_v_i++;
            }
        }
        //生产状态：0待生产，1开料，2钣金，3挂件喷涂，4发货
        $map2 .= " g.status_flow like '%\\_{$archives_status}|%' and ";

        $map2 .= "(g.status{$archives_status}_time between {$times[0]} and {$times[1]})";

        $field = "o.*,g.status as give_status2,FROM_UNIXTIME(g.status{$archives_status}_time,'%Y-%m-%d') as dates,count(g.id) as day_sum,sum(a.one_area) as area_day_sum";

        // 数据列表
        $data_list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field($field)
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($map)
            ->where($map2)
            ->group('dates,g.order_id')
            ->order('dates asc,g.order_pid asc')
            ->select();

        $group_date = '';
        $data_list_new = [];
        $i = count($data_list)-1;
        //小计
        $day_sum = 0;
        $area_day_sum = 0;
        $number_sum = 0;
        $area_sum = 0;
        $number_ok_sum = 0;
        $area_ok_sum = 0;
        $number_no_sum = 0;
        $area_no_sum = 0;
        //合计
        $all_day_sum = 0;
        $all_area_day_sum = 0;
        $all_number_sum = 0;
        $all_area_sum = 0;
        $all_number_ok_sum = 0;
        $all_area_ok_sum = 0;
        if(!empty($data_list)){
            foreach ($data_list as $k=>$v){
                //按时间合计分组
                if(empty($group_date))$group_date = $v['dates'];

                //总数
                $where = ['order_id'=>$v['id']];
                $stat = Db::name('mill_order_archives')->field('sum(number) as number_sum,sum((number*one_area)) as area_sum')->where($where)->find();

                $v['number_sum'] = $stat['number_sum'];
                $v['area_sum'] = round($stat['area_sum'],6);

                //完成数
                $where = [['g.order_id','=',$v['id']],['g.quality_status','>=',0],['g.status_flow','like',"%\\_{$archives_status}|%"]];
                $stat_ok = Db::name('mill_order_archives_give')->alias('g')->field('count(g.id) as number_sum,sum(a.one_area) as area_sum')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->find();

                $v['number_ok_sum'] = $stat_ok['number_sum'];
                $v['area_ok_sum'] = round($stat_ok['area_sum'],6);

                //未完成数
                $v['number_no_sum'] = $v['number_sum']-$v['number_ok_sum'];
                $v['area_no_sum'] = $v['area_sum']-$v['area_ok_sum'];
                $v['area_no_sum'] = round($v['area_no_sum'],6);

                //跳转
                //read_type 1:日产产品明细 2:剩余产品明细
                $url_parm = "?_s=g.status={$archives_status}|g.archives_sn={$v['archives_sn']}|times=".$v['dates'].urldecode(' - ').$v['dates']."&_o=g.status=eq|g.archives_sn=like|times=between%20time";
                $v['day_sum_str'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>$archives_status,'read_type'=>'1')).$url_parm.'">'.$v['day_sum'].'</a>';
                $url_parm = "?_s=g.archives_sn={$v['archives_sn']}&_o=g.archives_sn=like";
                $v['number_no_sum_str'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>$archives_status,'read_type'=>'2')).$url_parm.'">'.$v['number_no_sum'].'</a>';

                //按时间合计分组
                if($group_date != $v['dates']){

                    //小计
                    $group_val = [
                        'engineering'       =>  "{$group_date} 小计",
                        'day_sum_str'       =>  $day_sum,
                        'area_day_sum'      =>  $area_day_sum,
                        'number_sum'        =>  $number_sum,
                        'area_sum'          =>  $area_sum,
                        'number_ok_sum'     =>  $number_ok_sum,
                        'area_ok_sum'       =>  $area_ok_sum,
                        'number_no_sum_str' =>  $number_no_sum,
                        'area_no_sum'       =>  $area_no_sum,
                        'create_time'       =>  0,
                    ];
                    $data_list_new[] = $group_val;

                    //重置
                    $day_sum = 0;
                    $area_day_sum = 0;
                    $number_sum = 0;
                    $area_sum = 0;
                    $number_ok_sum = 0;
                    $area_ok_sum = 0;
                    $number_no_sum = 0;
                    $area_no_sum = 0;
                    $group_date = $v['dates'];
                }

                //小计
                $day_sum += $v['day_sum'];
                $area_day_sum += $v['area_day_sum'];
                $number_sum += $v['number_sum'];
                $area_sum += $v['area_sum'];
                $number_ok_sum += $v['number_ok_sum'];
                $area_ok_sum += $v['area_ok_sum'];
                $number_no_sum += $v['number_no_sum'];
                $area_no_sum += $v['area_no_sum'];
                //合计
                $all_day_sum += $v['day_sum'];
                $all_area_day_sum += $v['area_day_sum'];
                $all_number_sum += $v['number_sum'];
                $all_area_sum += $v['area_sum'];
                $all_number_ok_sum += $v['number_ok_sum'];
                $all_area_ok_sum += $v['area_ok_sum'];

                $data_list_new[] = $v;
                //最后一条记录
                if($i == $k){

                    //小计
                    $group_val = [
                        'engineering'       =>  "{$group_date} 小计",
                        'day_sum_str'       =>  $day_sum,
                        'area_day_sum'      =>  $area_day_sum,
                        'number_sum'        =>  $number_sum,
                        'area_sum'          =>  $area_sum,
                        'number_ok_sum'     =>  $number_ok_sum,
                        'area_ok_sum'       =>  $area_ok_sum,
                        'number_no_sum_str' =>  $number_no_sum,
                        'area_no_sum'       =>  $area_no_sum,
                        'create_time'       =>  0,
                    ];
                    $data_list_new[] = $group_val;
                    //合计
                    $group_val = [
                        'engineering'       =>  "合计",
                        'day_sum_str'       =>  $all_day_sum,
                        'area_day_sum'      =>  $all_area_day_sum,
                        'number_sum'        =>  $all_number_sum,
                        'area_sum'          =>  $all_area_sum,
                        'number_ok_sum'     =>  $all_number_ok_sum,
                        'area_ok_sum'       =>  $all_area_ok_sum,
                        'create_time'       =>  0,
                    ];
                    $data_list_new[] = $group_val;
                }
            }
        }

        $status_arr = [1=>'开料',2=>'钣金',3=>'喷涂'];
        $title = '统计';
        if($archives_status)$title = $status_arr[$archives_status].$title;
        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                //['select:2', 'g.status_flow', '车间','',$archives_status,$status_arr],
                ['text:2', 'o.archives_sn', '档案号', 'like'],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'times', '日期','',date('Y-m-d',$times[0]).' - '.date('Y-m-d',$times[1])],
            ])
            ->addColumns([ // 批量添加列
                ['dates', '日期'],
                ['archives_sn', '档案号'],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum','总数量(件)'],
                ['area_sum','总面积(M²)'],
                ['create_time','下单日期','date'],
                ['day_sum_str','日产量(件)'],
                ['area_day_sum','日产面积(M²)'],
                ['number_ok_sum','总完成数量(件)'],
                ['area_ok_sum','总完成面积(M²)'],
                ['number_no_sum_str','未完成数量(件)'],
                ['area_no_sum','未完成面积(M²)'],
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->setRowList($data_list_new) // 设置表格数据
            ->setColumnWidth([
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 生产线总统计
     */
    public function speedOver()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '生产统计';
        // 获取查询条件
        $map = $this->getMap();
        //默认日期：今天
        $times[0] = strtotime(date('Y-m-d'));
        $times[1] = strtotime(date('Y-m-d 23:59:59'));
        //$times[0] = 1648224000;
        //$times[1] = 1648569599;

        if(!empty($map)){
            $m_v_i = 0;
            foreach ($map as &$m_v){
                if (in_array('times',$m_v)){
                    $times[0] = strtotime($m_v[2][0]);
                    $times[1] = strtotime($m_v[2][1]);
                    unset($map[$m_v_i]);
                }

                $m_v_i++;
            }
        }
        $starttime = date('Y-m-d',$times[0]);
        $endtime = date('Y-m-d',$times[1]);

        $data_list = [];

        //小计
        $status1_sum = 0;
        $status1_area_sum = 0;
        $status2_sum = 0;
        $status2_area_sum = 0;
        $status3_sum = 0;
        $status3_area_sum = 0;
        $status4_sum = 0;
        $status4_area_sum = 0;
        //合计
        $all_status1_sum = 0;
        $all_status1_area_sum = 0;
        $all_status2_sum = 0;
        $all_status2_area_sum = 0;
        $all_status3_sum = 0;
        $all_status3_area_sum = 0;
        $all_status4_sum = 0;
        $all_status4_area_sum = 0;

        $day_i = (($times[1]+1)-$times[0])/86400;
        for ($i=0;$i<$day_i;$i++){
            //按天分组查询
            $day_start = $times[0] + ($i*86400);
            $day_end = strtotime(date('Y-m-d 23:59:59',$day_start));
            $day = date('Y-m-d',$day_start);

            $map2 = "((g.status1_time between {$day_start} and {$day_end}) OR (g.status2_time between {$day_start} and {$day_end}) OR (g.status3_time between {$day_start} and {$day_end}) OR (g.status4_time between {$day_start} and {$day_end}))";
            $order_list = Db::name('mill_order_archives_give')
                ->alias('g')
                ->field('o.*')
                ->leftJoin('mill_order o','o.id=g.order_id')
                ->where($map)
                ->where($map2)
                ->group('o.id')
                ->order('o.id asc')
                ->select();

            if(!empty($order_list)){
                foreach ($order_list as &$v){

                    $v['dates'] = $day;

                    $archvices = ArchivesModel::getOneStat($v['id'],'order_id','eq','',[$day_start,$day_end]);

                    $v = array_merge($v,$archvices);

                    //小计
                    $status1_sum += $v['status1'];
                    $status1_area_sum += $v['status1_area_sum'];
                    $status2_sum += $v['status2'];
                    $status2_area_sum += $v['status2_area_sum'];
                    $status3_sum += $v['status3'];
                    $status3_area_sum += $v['status3_area_sum'];
                    $status4_sum += $v['status4'];
                    $status4_area_sum += $v['status4_area_sum'];
                    //合计
                    $all_status1_sum += $v['status1'];
                    $all_status1_area_sum += $v['status1_area_sum'];
                    $all_status2_sum += $v['status2'];
                    $all_status2_area_sum += $v['status2_area_sum'];
                    $all_status3_sum += $v['status3'];
                    $all_status3_area_sum += $v['status3_area_sum'];
                    $all_status4_sum += $v['status4'];
                    $all_status4_area_sum += $v['status4_area_sum'];

                    $data_list[] = $v;
                }

                //小计
                $group_val = [
                    'area_sum'       =>  "小计",
                    'status1'           =>  $status1_sum,
                    'status1_area_sum'  =>  $status1_area_sum,
                    'status2'           =>  $status2_sum,
                    'status2_area_sum'  =>  $status2_area_sum,
                    'status3'           =>  $status3_sum,
                    'status3_area_sum'  =>  $status3_area_sum,
                    'status4'           =>  $status4_sum,
                    'status4_area_sum'  =>  $status4_area_sum,
                    'create_time'       =>  0,
                ];
                $data_list[] = $group_val;

                //重置
                $status1_sum = 0;
                $status1_area_sum = 0;
                $status2_sum = 0;
                $status2_area_sum = 0;
                $status3_sum = 0;
                $status3_area_sum = 0;
                $status4_sum = 0;
                $status4_area_sum = 0;

            }

        }
        if(!empty($data_list)){

            //合计
            $group_val = [
                'area_sum'       =>  "合计",
                'status1'           =>  $all_status1_sum,
                'status1_area_sum'  =>  $all_status1_area_sum,
                'status2'           =>  $all_status2_sum,
                'status2_area_sum'  =>  $all_status2_area_sum,
                'status3'           =>  $all_status3_sum,
                'status3_area_sum'  =>  $all_status3_area_sum,
                'status4'           =>  $all_status4_sum,
                'status4_area_sum'  =>  $all_status4_area_sum,
                'create_time'       =>  0,
            ];
            $data_list[] = $group_val;
        }

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    var wrapper_height = $("#builder-table-wrapper").css("max-height");
                    wrapper_height = parseInt(wrapper_height) + 30;
                    $("#builder-table-wrapper").css("max-height",wrapper_height+"px");
                    var table_head_html = \'<tr>\' +
                        \'<th colspan="1">日期</th>\' +
                        \'<th colspan="1">档案号</th>\' +
                        \'<th colspan="1">工程名称</th>\' +
                        \'<th colspan="1">批次</th>\' +
                        \'<th colspan="1">产品总量</th>\' +
                        \'<th colspan="1">总面积</th>\' +
                        \'<th colspan="2">开料</th>\' +
                        \'<th colspan="2">钣金</th>\' +
                        \'<th colspan="2">喷涂</th>\' +
                        \'<th colspan="2">发货</th>\' +
                        \'<th colspan="1">总完成数量</th>\' +
                        \'<th colspan="1">总完成面积</th>\' +
                        \'<th colspan="1">未完成数量</th>\' +
                        \'</tr>\';
                    $("#builder-table-head table thead").html(table_head_html+$("#builder-table-head table thead").html());
                    $("#builder-table-right-head table thead").html(table_head_html+$("#builder-table-right-head table thead").html());
                            
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['text:2', 'o.archives_sn', '档案号', 'like'],
                ['daterange:2', 'times', '日期','',"{$starttime} - {$endtime}"],
            ])
            ->addColumns([ // 批量添加列
                ['dates', ''],
                ['archives_sn', ''],
                ['engineering', ''],
                ['batch', ''],
                ['number_sum', ''],
                ['area_sum',''],
                ['status1','日产量'],
                ['status1_area_sum','日产面积'],
                ['status2','日产量'],
                ['status2_area_sum','日产面积'],
                ['status3','日产量'],
                ['status3_area_sum','日产面积'],
                ['status4','日产量'],
                ['status4_area_sum','日产面积'],
                ['number_ok_sum',''],
                ['area_ok_sum',''],
                ['number_on_sum',''],
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    /**
     * 生产线产品明细
     */
    public function speedMore(){
        $input = input();
        $action = new Give();

        return $action->speed($input['archives_status'],$input['read_type']);
    }
    /**
     * 开料统计
     * @return mixed
     */
    public function cutting()
    {
        return $this->speed(1);
    }
    /**
     * 钣金统计
     * @return mixed
     */
    public function plate()
    {
        return $this->speed(2);
    }
    /**
     * 挂件喷涂统计
     * @return mixed
     */
    public function spray()
    {
        return $this->speed(3);
    }

    /**
     * 销售部统计
     * @return mixed
     */
    public function sales()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '销售统计';
        // 获取查询条件
        $map = $this->getMap();
        //默认12个月
        $starttime = strtotime('-1 year',strtotime(date('Y-m-d')));
        $endtime = strtotime(date('Y-m-d 23:59:59'));
        $map_time = [['o.create_time','between',"{$starttime},{$endtime}"]];
        $starttime = date('Y-m-d',$starttime);
        $endtime = date('Y-m-d',$endtime);

        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'o.create_time'){
                    $map_time = [$v];
                    $starttime = date('Y-m-d',strtotime($v[2][0]));
                    $endtime = date('Y-m-d',strtotime($v[2][1]));
                    unset($map[$k]);
                }
            }
        }
        $title .= "{$starttime}-{$endtime}";
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('c.*,COUNT(DISTINCT c.id) as client_sum,COUNT(DISTINCT o.id) as order_sum,group_concat(DISTINCT o.id) as order_ids')
            ->leftJoin('mill_client c','o.client_id=c.id')
            ->where($map)
            ->where($map_time)
            ->group('c.sales')
            ->order('order_sum desc,client_sum desc')
            ->paginate()
            ->each(function ($v){

                $archvices = Db::name('mill_order_archives')
                    ->alias('a')
                    ->field('SUM(a.number) as number_sum,SUM(a.one_area*a.number) as area_sum')
                    ->where([['a.order_id','in',$v['order_ids']]])
                    ->find();
                $v = array_merge($v,$archvices);
                //完成数
                $v['area_ok_sum'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('count(g.id) as number_sum,sum(a.one_area) as area_sum')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where([['a.order_id','in',$v['order_ids']],['g.quality_status','>=',0],['g.status','>=',3]])
                    ->sum('a.one_area');

                $v['area_sum'] = round($v['area_sum']);
                $v['area_ok_sum'] = round($v['area_ok_sum']);

                $v['area_no_sum'] = $v['area_sum']-$v['area_ok_sum'];

                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('销售统计') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['text:2', 'c.sales', '销售经理名称', 'like'],
                ['daterange:2', 'o.create_time', '日期','',"{$starttime} - {$endtime}"],
            ])
            ->addColumns([ // 批量添加列
                ['sales', '销售经理名称'],
                ['client_sum', '总客户数量'],
                ['order_sum', '总订单数量'],
                ['number_sum', '产品总单数'],
                ['area_sum','总面积 M²'],
                ['area_ok_sum','已完成面积 M²'],
                ['area_no_sum','未完成面积 M²'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->addRightButton('client',['title' => '查看客户','href' => url('mill/index/client').'?_s=c.sales=__sales__&_o=sales=like','class'=>'btn btn-primary disable-dch','icon'=>''])
            ->addRightButton('index',['title' => '查看订单','href' => url('mill/order/index').'?_s=c.sales=__sales__&_o=sales=like','data-files'=>'archivesEdit','class'=>'btn bg-info-light disable-dch','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    /**
     * 设计部统计
     * @return mixed
     */
    public function archives()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '设计统计';
        // 获取查询条件
        $map = $this->getMap();
        //默认12个月
        $starttime = strtotime('-1 year',strtotime(date('Y-m-01')));
        $endtime = strtotime(date('Y-m-d 23:59:59'));

        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'o.archives_sign_time'){
                    $starttime = strtotime($v[2][0]);
                    $endtime = strtotime($v[2][1]);
                    unset($map[$k]);
                }
            }
        }

        //按月统计：时间差
        $day_time = abs(date('Y',$endtime+1)-date('Y',$starttime)) * 12 + abs(date('m',$endtime+1)-date('m',$starttime));

        $starttime2 = date('Y-m-d',$starttime);
        $endtime2 = date('Y-m-d',$endtime);
        $title .= "{$starttime2}-{$endtime2}";

        $count_arr = [
            'id'                =>  '',
            'date_title'        =>  '合计',
            'order_sum'         =>  0,
            'number_sum'        =>  0,
            'area_sum'          =>  0,
            'area_ok_sum'       =>  0,
            'area_no_sum'       =>  0,
            'starttime'         =>  $starttime2,
            'endtime'           =>  $endtime2,
        ];

        while (1 <= $day_time) {

            $new_date = date('Y-m-01', strtotime("-{$day_time} month",strtotime(date('Y-m-01',($endtime + 1)))));
            $end_date = date('Y-m-d H:i:s',strtotime("+1 month",strtotime($new_date))-1);

            //条件
            $map_time = [['o.archives_sign_time','between time',"{$new_date},{$end_date}"]];

            $info = Db::name('mill_order')
                ->alias('o')
                ->field('o.*,COUNT(DISTINCT o.id) as client_sum,COUNT(DISTINCT o.id) as order_sum,group_concat(DISTINCT o.id) as order_ids')
                ->where($map)
                ->where($map_time)
                ->order('order_sum desc,client_sum desc')
                ->find();

            $archvices = Db::name('mill_order_archives')
                ->alias('a')
                ->field('SUM(a.number) as number_sum,SUM(a.one_area*a.number) as area_sum')
                ->where([['a.order_id','in',$info['order_ids']]])
                ->find();
            $info = array_merge($info,$archvices);
            //完成数
            $info['area_ok_sum'] = Db::name('mill_order_archives_give')
                ->alias('g')
                ->field('count(g.id) as number_sum,sum(a.one_area) as area_sum')
                ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                ->where([['a.order_id','in',$info['order_ids']],['g.quality_status','>=',0],['g.status','>=',3]])
                ->sum('a.one_area');
            $info['area_no_sum'] = $info['area_sum']-$info['area_ok_sum'];

            $info['date_title'] = date('Y年m月',strtotime($new_date));
            $info['starttime'] = $new_date;
            $info['endtime'] = date('Y-m-d',strtotime($end_date));

            $count_arr['order_sum'] += $info['order_sum'];
            $count_arr['number_sum'] += $info['number_sum'];
            $count_arr['area_sum'] += $info['area_sum'];
            $count_arr['area_ok_sum'] += $info['area_ok_sum'];
            $count_arr['area_no_sum'] += $info['area_no_sum'];

            $data_list[] = $info;
            --$day_time;
        }
        $data_list[] = $count_arr;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('设计统计') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['daterange:2', 'o.archives_sign_time', '日期','',"{$starttime2} - {$endtime2}"],
            ])
            ->addColumns([ // 批量添加列
                ['date_title', '日期'],
                ['order_sum', '面积表总数'],
                ['number_sum', '产品总数量'],
                ['area_sum','总面积 M²'],
                ['area_ok_sum','已完成面积 M²'],
                ['area_no_sum','未完成面积 M²'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->addRightButton('client',['title' => '查看客户','href' => url('mill/index/client').'?_s=c.create_time=__starttime__ - __endtime__&_o=o.archives_plan=like|c.create_time=between time','class'=>'btn btn-primary disable-dch','icon'=>''])
            ->addRightButton('index',['title' => '查看订单','href' => url('mill/order/index').'?_s=o.archives_sign_time=__starttime__ - __endtime__&_o=o.archives_sign_time=between time','data-files'=>'archivesEdit','class'=>'btn bg-info-light disable-dch','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    public function archives_old()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '设计统计';
        // 获取查询条件
        $map = $this->getMap();
        //默认12个月
        $starttime = strtotime('-1 year',strtotime(date('Y-m-d')));
        $endtime = strtotime(date('Y-m-d 23:59:59'));
        $map_time = [['o.archives_sign_time','between',"{$starttime},{$endtime}"]];
        $starttime = date('Y-m-d',$starttime);
        $endtime = date('Y-m-d',$endtime);

        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'o.archives_sign_time'){
                    $map_time = [$v];
                    $starttime = date('Y-m-d',strtotime($v[2][0]));
                    $endtime = date('Y-m-d',strtotime($v[2][1]));
                    unset($map[$k]);
                }
            }
        }
        $title .= "{$starttime}-{$endtime}";
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,COUNT(DISTINCT o.id) as client_sum,COUNT(DISTINCT o.id) as order_sum,group_concat(DISTINCT o.id) as order_ids')
            ->where($map)
            ->where($map_time)
            ->group('o.archives_plan')
            ->order('order_sum desc,client_sum desc')
            ->paginate()
            ->each(function ($v){

                $archvices = Db::name('mill_order_archives')
                    ->alias('a')
                    ->field('SUM(a.number) as number_sum,SUM(a.one_area*a.number) as area_sum')
                    ->where([['a.order_id','in',$v['order_ids']]])
                    ->find();
                $v = array_merge($v,$archvices);
                //完成数
                $v['area_ok_sum'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('count(g.id) as number_sum,sum(a.one_area) as area_sum')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where([['a.order_id','in',$v['order_ids']],['g.quality_status','>=',0],['g.status','>=',3]])
                    ->sum('a.one_area');
                $v['area_no_sum'] = $v['area_sum']-$v['area_ok_sum'];

                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('设计统计') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['text:2', 'o.archives_plan', '计师名称', 'like'],
                ['daterange:2', 'o.archives_sign_time', '日期','',"{$starttime} - {$endtime}"],
            ])
            ->addColumns([ // 批量添加列
                ['archives_plan', '设计师名称'],
                ['order_sum', '面积表总数'],
                ['number_sum', '产品总数量'],
                ['area_sum','总面积 M²'],
                ['area_ok_sum','已完成面积 M²'],
                ['area_no_sum','未完成面积 M²'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->addRightButton('client',['title' => '查看客户','href' => url('mill/index/client').'?_s=o.archives_plan=__archives_plan__&_o=o.archives_plan=like','class'=>'btn btn-primary disable-dch','icon'=>''])
            ->addRightButton('index',['title' => '查看订单','href' => url('mill/order/index').'?_s=o.archives_plan=__archives_plan__&_o=o.archives_plan=like','data-files'=>'archivesEdit','class'=>'btn bg-info-light disable-dch','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    /**
     * 发货部统计
     * @return mixed
     */
    public function deliver()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '发货统计';
        // 获取查询条件
        $map = $this->getMap();
        //默认12个月
        $starttime = strtotime('-1 year',strtotime(date('Y-m-01')));
        $endtime = strtotime(date('Y-m-d 23:59:59'));

        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'g.address_time'){
                    $map_time = [$v];
                    $starttime = date('Y-m-d',strtotime($v[2][0]));
                    $endtime = date('Y-m-d',strtotime($v[2][1]));
                    unset($map[$k]);
                }
            }
        }

        //按月统计：时间差
        $day_time = abs(date('Y',$endtime+1)-date('Y',$starttime)) * 12 + abs(date('m',$endtime+1)-date('m',$starttime));

        $starttime2 = date('Y-m-d',$starttime);
        $endtime2 = date('Y-m-d',$endtime);
        $title .= "{$starttime2}-{$endtime2}";

        $count_arr = [
            'id'                =>  '',
            'date_title'        =>  '合计',
            'number_sum'        =>  0,
            'area_sum'          =>  0,
            'starttime'         =>  $starttime2,
            'endtime'           =>  $endtime2,
        ];

        while (1 <= $day_time) {

            $new_date = date('Y-m-01', strtotime("-{$day_time} month",strtotime(date('Y-m-01',($endtime + 1)))));
            $end_date = date('Y-m-d H:i:s',strtotime("+1 month",strtotime($new_date))-1);

            //条件
            $map_time = [['g.address_time','between time',"{$new_date},{$end_date}"]];

            $info = Db::name('mill_order_archives_give')
                ->alias('g')
                ->field("g.*,COUNT(g.id) AS number_sum,SUM(a.one_area) AS area_sum")
                ->leftJoin('mill_order_archives a','g.archives_id=a.id')
                ->where($map)
                ->where($map_time)
                ->where("g.status=4 and g.address_status in (1,2)")
                ->find();

            $info['date_title'] = date('Y年m月',strtotime($new_date));
            $info['starttime'] = $new_date;
            $info['endtime'] = date('Y-m-d',strtotime($end_date));

            $count_arr['number_sum'] += $info['number_sum'];
            $count_arr['area_sum'] += $info['area_sum'];

            $data_list[] = $info;
            --$day_time;
        }
        $data_list[] = $count_arr;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('发货统计') // 页面标题
            ->setTableName('mill_order_archives_give') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['daterange:2', 'g.address_time', '日期','',"{$starttime2} - {$endtime2}"],
            ])
            ->addColumns([ // 批量添加列
                ['date_title', '日期'],
                ['number_sum', '发货数量'],
                ['area_sum','发货面积 M²'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->addRightButton('deliverShow',['title' => '查看明细','href' => url('mill/order/deliver').'?_s=g.address_time=__starttime__ - __endtime__&_o=g.address_time=between time','class'=>'btn btn-primary disable-dch','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    public function deliver_old()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '发货统计';
        // 获取查询条件
        $map = $this->getMap();
        //默认12个月
        $starttime = strtotime('-1 year',strtotime(date('Y-m-d')));
        $endtime = strtotime(date('Y-m-d 23:59:59'));
        $map_time = [['g.address_time','between',"{$starttime},{$endtime}"]];
        $starttime = date('Y-m-d',$starttime);
        $endtime = date('Y-m-d',$endtime);

        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'g.address_time'){
                    $map_time = [$v];
                    $starttime = date('Y-m-d',strtotime($v[2][0]));
                    $endtime = date('Y-m-d',strtotime($v[2][1]));
                    unset($map[$k]);
                }
            }
        }
        $title .= "{$starttime}-{$endtime}";
        $data_list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field("g.*,COUNT(g.id) AS number_sum,SUM(a.one_area) AS area_sum,c.plate_number")
            ->leftJoin('mill_order_archives a','g.archives_id=a.id')
            ->leftJoin('mill_car c','g.car_id=c.id')
            ->where($map)
            ->where($map_time)
            ->where("g.status=4 and g.address_status in (1,2)")
            ->group("g.address_sn")
            ->order('g.address_sn desc')
            ->paginate()
            /*->each(function ($v){

                $where = ['order_id'=>$v['id']];
                $v['give_sum'] = Db::name('mill_order_archives_give')->where($where)->where("quality_status>'-2'")->count();
                $v['give_sum4'] = Db::name('mill_order_archives_give')->where($where)->where('status=4')->count();
                $v['give_sum0_4'] = $v['give_sum']-$v['give_sum4'];

                return $v;
            })*/
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('发货统计') // 页面标题
            ->setTableName('mill_order_archives_give') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['daterange:2', 'g.address_time', '日期','',"{$starttime} - {$endtime}"],
            ])
            ->addColumns([ // 批量添加列
                ['address_sn', '发货单号'],
                ['address_time', '发货时间','datetime'],
                ['number_sum', '发货数量'],
                ['area_sum','发货面积 M²'],
                ['plate_number','车辆'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->addRightButton('deliverShow',['title' => '查看明细','href' => url('mill/order/deliverShow',['id'=>'__order_id__','address_sn' => '__address_sn__','status'=>'4']),'class'=>'btn btn-primary disable-dch','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    /**
     * 生产部统计
     * @return mixed
     */
    public function give()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '生产统计';
        // 获取查询条件
        $map = $this->getMap();
        //默认12个月
        $starttime = strtotime('-1 year',strtotime(date('Y-m-d')));
        $endtime = strtotime(date('Y-m-d 23:59:59'));
        /*$map_time = [['o.archives_sign_time','between',"{$starttime},{$endtime}"]];
        $starttime = date('Y-m-d',$starttime);
        $endtime = date('Y-m-d',$endtime);

        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'o.archives_sign_time'){
                    $map_time = [$v];
                    $starttime = date('Y-m-d',strtotime($v[2][0]));
                    $endtime = date('Y-m-d',strtotime($v[2][1]));
                    unset($map[$k]);
                }
            }
        }*/
        //$title .= "{$starttime}-{$endtime}";
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*')
            ->where($map)
            //->where($map_time)
            ->order('o.status_time desc,o.archives_sign_time desc')
            ->paginate()
            ->each(function ($v){

                $archvices = ArchivesModel::getOneStat($v['id']);
                $v = array_merge($v,$archvices);

                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    var wrapper_height = $("#builder-table-wrapper").css("max-height");
                    wrapper_height = parseInt(wrapper_height) + 30;
                    $("#builder-table-wrapper").css("max-height",wrapper_height+"px");
                    var table_head_html = \'<tr>\' +
                        \'<th colspan="1">档案号</th>\' +
                        \'<th colspan="1">项目名称</th>\' +
                        \'<th colspan="1">批次</th>\' +
                        \'<th colspan="1">产品总量</th>\' +
                        \'<th colspan="1">面积</th>\' +
                        \'<th colspan="4">开料</th>\' +
                        \'<th colspan="4">钣金</th>\' +
                        \'<th colspan="4">喷涂</th>\' +
                        \'<th colspan="4">发货</th>\' +
                        \'<th colspan="1">审核日期</th>\' +
                        \'<th colspan="1">签字日期</th>\' +
                        \'<th colspan="1" class="disable-dch">操作</th>\' +
                        \'</tr>\';
                    $("#builder-table-head table thead").html(table_head_html+$("#builder-table-head table thead").html());
                    $("#builder-table-right-head table thead").html(table_head_html+$("#builder-table-right-head table thead").html());
                    //$("#builder-table-right").css("top","50px");
                    $("#builder-table-right-body").css("margin-top","100px");
                    var right_height = $("#builder-table-right").css("height");
                    console.log(right_height);
                    right_height = parseInt(right_height) + 50;
                    console.log(right_height);
                    $("#builder-table-right").css("height",right_height+"px");
                            
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('销售统计') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['text:2', 'o.archives_sn', '档案号', 'like'],
                //['daterange:2', 'o.archives_sign_time', '日期','',"{$starttime} - {$endtime}"],
            ])
            ->addColumns([ // 批量添加列
                ['archives_sn', ''],
                ['engineering', ''],
                ['batch', ''],
                ['number_sum', ''],
                ['area_sum',''],
                ['status1','已开料'],
                ['status1_no','未开料'],
                ['status1_area_sum','已开面积'],
                ['status1_area_on_sum','未开面积'],
                ['status2','完成钣金'],
                ['status2_no','未完成钣金'],
                ['status2_area_sum','完成面积'],
                ['status2_area_on_sum','未完成面积'],
                ['status3','已喷涂'],
                ['status3_no','未喷涂'],
                ['status3_area_sum','已喷涂面积'],
                ['status3_area_on_sum','未喷涂面积'],
                ['status4','已发'],
                ['status4_no','未发'],
                ['status4_area_sum','已发面积'],
                ['status4_area_on_sum','未发面积'],
                ['status_time','','date'],
                ['archives_sign_time','','date'],
                ['right_button', '', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->fixedRight(3)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->addRightButton('cutting',['title' => '明细','href' => url('mill/give/cutting').'?_s=g.status=0|g.archives_sn=__archives_sn__&_o=g.status=eq|g.archives_sn=like','class'=>'btn btn-primary disable-dch','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    /**
     * 生产周期统计
     * @return mixed
     */
    public function cycle()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '生产周期';
        // 获取查询条件
        $map = $this->getMap();
        $status = 1;
        if(!empty($map)){
            $m_v_i = 0;
            foreach ($map as &$m_v){
                if (in_array('times',$m_v)){
                    $times[0] = strtotime($m_v[2][0]);
                    $times[1] = strtotime($m_v[2][1]);
                    unset($map[$m_v_i]);
                }
                elseif (in_array('status',$m_v)){
                    $status = $m_v[2];
                    unset($map[$m_v_i]);
                }

                $m_v_i++;
            }
        }
        $map = array_merge($map);
        $map[] = ['g.status_flow','like',"%\\_{$status}|%"];


        if($status == 1){
            $start_status = $status;
            $count_day = "(
                SUBSTRING_INDEX(GROUP_CONCAT(g.status{$start_status}_time ORDER BY g.status{$start_status}_time DESC),',',1)
                -
                o.status_time
            )/86400";
        }
        else{
            $start_status = $status;
            $end_status = $status-1;
            $count_day = "(
                SUBSTRING_INDEX(GROUP_CONCAT(g.status{$start_status}_time ORDER BY g.status{$start_status}_time DESC),',',1)
                -
                SUBSTRING_INDEX(GROUP_CONCAT(g.status{$end_status}_time ORDER BY g.status{$end_status}_time DESC),',',1)
            )/86400";
        }

        //1000平方以外，算7天
        $cycle_area = 1000;
        $cycle_day = 7;
        $cycle_day2 = 3;//1000平方以内，算3天

        //$field = "o.id,a.area_sum,a.number_sum,CEILING({$count_day}) AS count_day,{$status} as status_map,{$cycle_area} as cycle_area,{$cycle_day} as cycle_day,{$cycle_day2} as cycle_day2,GROUP_CONCAT(g.status{$status}_time) as cycle_time";
        $field = "o.id,a.area_sum,a.number_sum,CEILING({$count_day}) AS count_day,{$status} as status_map,{$cycle_area} as cycle_area,{$cycle_day} as cycle_day,{$cycle_day2} as cycle_day2,g.status as cycle_status";
        $order = "( CASE 
        
        -- 超过7天排最前
        WHEN (({$count_day}) > {$cycle_day}) THEN convert({$count_day}*1000000000000,unsigned) 
        -- 其次是1000平方以内，3天以上
        WHEN (a.area_sum > {$cycle_area} AND (({$count_day}) > {$cycle_day2})) THEN convert({$count_day}*1000000000000,unsigned) 
        -- 最后按扫码时间排
        ELSE convert(GROUP_CONCAT(g.status{$start_status}_time ORDER BY g.status{$start_status}_time DESC),unsigned) 
        
        END ) DESC";
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field($field)
            ->leftJoin('mill_order_archives_give g','g.order_id=o.id')
            ->leftJoin('mill_order_archives_sum a','a.order_id=o.id')
            ->where($map)
            ->group('g.order_id')
            ->orderRaw($order)
            ->paginate()
            ->each(function ($v){

                $data = Db::name('mill_order')->where(['id'=>$v['id']])->find();

                $v["status_area_sum"] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where(['g.order_id'=>$v['id']])->sum('a.one_area');

                $v["status_area_sum"] = round($v["status_area_sum"],6);
                $v["status_area_on_sum"] = abs(round($v['area_sum']-$v["status_area_sum"],6));

                $v = array_merge($v,$data);

                $v['cycle'] = '销售部未审核';

                if(!empty($v['status_time'])){

                    //if(empty($v['cycle_time']))$v['cycle'] = '未生产';
                    if($v['cycle_status'] < $v['status_map'])$v['cycle'] = '未生产';
                    else {
                        if($v['count_day'] <= 1)$v['count_day'] = 1;
                        $v['cycle'] = "{$v['count_day']}";

                        if(($v['count_day'] > $v['cycle_day']) || ($v['area_sum'] > $v['cycle_area'] && $v['count_day'] > $v['cycle_day2']))$v['cycle'] .= "天<br><span class='label label-primary'>超期</span>";
                        else $v['cycle'] .= "天<br><span class='label label-success'>未超期</span>";

                    }

                }
                return $v;
            })
        ;

        /*// 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*')
            ->where($map)
            ->order('o.status_time desc,o.archives_sign_time desc')
            ->paginate()
            ->each(function ($v){

                $archvices = ArchivesModel::getOneStat($v['id']);
                $v = array_merge($v,$archvices);

                $v['cycle1'] = $v['cycle2'] = $v['cycle3'] = $v['cycle4'] = '销售部未审核';
                $cycle_start = $v['status_time'];
                $cycle1 = Db::name('mill_order_archives_give')->where(['order_id'=>$v['id']])->order('status1_time desc')->value('status1_time');
                $cycle2 = Db::name('mill_order_archives_give')->where(['order_id'=>$v['id']])->order('status2_time desc')->value('status2_time');
                $cycle3 = Db::name('mill_order_archives_give')->where(['order_id'=>$v['id']])->order('status3_time desc')->value('status3_time');
                $cycle4 = Db::name('mill_order_archives_give')->where(['order_id'=>$v['id']])->order('status4_time desc')->value('status4_time');

                //1000平方以内，算3天
                //1000平方以外，算7天
                $cycle_day = 7;
                if($v['area_sum'] <1000)$cycle_day = 3;

                if(empty($cycle_start)){
                    $v['cycle1'] = $v['cycle2'] = $v['cycle3'] = $v['cycle4'] = '未审核';
                }
                else{
                    if(empty($cycle1))$v['cycle1'] = '未开料';
                    else {
                        $v['cycle1'] = ceil(($cycle1-$cycle_start)/86400);
                        if($v['cycle1']>$cycle_day)$v['cycle1'] .= "天<br><span class='label label-primary'>超期</span>";
                        else $v['cycle1'] .= "天<br><span class='label label-success'>未超期</span>";

                    }
                    if(empty($cycle2))$v['cycle2'] = '未钣金';
                    else {
                        $v['cycle2'] = ceil(($cycle2-$cycle1)/86400);
                        if($v['cycle2']>$cycle_day)$v['cycle2'] .= "天<br><span class='label label-primary'>超期</span>";
                        else $v['cycle2'] .= "天<br><span class='label label-success'>未超期</span>";
                    }
                    if(empty($cycle3))$v['cycle3'] = '未喷涂';
                    else {
                        $v['cycle3'] = ceil(($cycle3-$cycle2)/86400);
                        if($v['cycle3']>$cycle_day)$v['cycle3'] .= "天<br><span class='label label-primary'>超期</span>";
                        else $v['cycle3'] .= "天<br><span class='label label-success'>未超期</span>";
                    }
                    if(empty($cycle4))$v['cycle4'] = '未发货';
                    else {
                        $v['cycle4'] = ceil(($cycle4-$cycle3)/86400);
                        if($v['cycle4']>$cycle_day)$v['cycle4'] .= "天<br><span class='label label-primary'>超期</span>";
                        else $v['cycle4'] .= "天<br><span class='label label-success'>未超期</span>";
                    }
                }


                return $v;
            })
        ;*/

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        $give_status_search = GiveModel::$give_status_search;
        unset($give_status_search[0]);
        unset($give_status_search[4]);
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('生产周期') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['select:2', 'status', '生产状态','','1',$give_status_search],
                ['text:2', 'g.archives_sn', '档案号', 'like'],
                //['daterange:2', 'o.archives_sign_time', '日期','',"{$starttime} - {$endtime}"],
            ])
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案号'],
                ['engineering', '项目名称'],
                ['batch', '批次'],
                ['number_sum', '产品总量'],
                ['area_sum','总面积'],
                ['cycle','超期状态'],
                ['status_area_sum','已开面积'],
                ['status_area_on_sum','未开面积'],
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            //->fixedRight(3)
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    /**
     * 生产统计
     * @return mixed
     */
    public function schedul($status = 1)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '生产计划';
        // 获取查询条件
        $map = $this->getMap();
        //$status = 1;
        //默认日期：今天
        $times[0] = strtotime(date('Y-m-d'));
        $times[1] = strtotime(date('Y-m-d 23:59:59'));

        if(!empty($map)){
            $m_v_i = 0;
            foreach ($map as &$m_v){
                if (in_array('times',$m_v)){
                    $times[0] = strtotime($m_v[2][0]);
                    $times[1] = strtotime($m_v[2][1]);
                    unset($map[$m_v_i]);
                }
                elseif (in_array('status',$m_v)){
                    $status = $m_v[2];
                    unset($map[$m_v_i]);
                }

                $m_v_i++;
            }
        }
        $map = array_merge($map);
        $starttime = date('Y-m-d',$times[0]);
        $endtime = date('Y-m-d',$times[1]);

        $data_list = [];

        //小计
        $status_sum = 0;
        $status_area_sum = 0;
        //合计
        $all_status_sum = 0;
        $all_status_area_sum = 0;

        $day_i = (($times[1]+1)-$times[0])/86400;
        for ($i=0;$i<$day_i;$i++){
            //按天分组查询
            $day_start = $times[0] + ($i*86400);
            $day_end = strtotime(date('Y-m-d 23:59:59',$day_start));
            $day = date('Y-m-d',$day_start);

            $map2 = "o.status{$status}_time between {$day_start} and {$day_end}";

            $order_id1 = Db::name('mill_order_archives_give')
                ->alias('o')
                ->where($map)
                ->where($map2)
                ->column('DISTINCT o.order_id');

            $map2 = "a.status < {$status} and o.give_status > 0";
            $order_id2 = Db::name('mill_order_archives')
                ->alias('a')
                ->where($map)
                ->where($map2)
                ->leftJoin('mill_order o','o.id=a.order_id')
                ->column('DISTINCT a.order_id');

            $map2 = "(o.give_status = {$status} and o.start_time between {$day_start} and {$day_end}) or (o.end_time between {$day_start} and {$day_end}) ";
            $order_id3 = Db::name('mill_order_plan')
                ->alias('o')
                ->where($map)
                ->where($map2)
                ->where("o.delete = 1")
                ->column('DISTINCT o.order_id');
            $order_ids = array_unique(array_merge($order_id1,$order_id2,$order_id3));

            $order_id_delete = Db::name('mill_order_plan')
                ->alias('o')
                ->where($map)
                ->where($map2)
                ->where("o.delete = 0")
                ->column('DISTINCT o.order_id');

            if(!empty($order_id_delete)){
                foreach ($order_id_delete as $del_id){
                    if(($key = array_search($del_id,$order_ids))){
                        unset($order_ids[$key]);
                    }
                }
            }
            $order_ids = implode(',',$order_ids);

            if(!empty($order_ids)){
                $map2 = "o.id in({$order_ids}) and o.give_status > 0";
                $order_list = Db::name('mill_order')
                    ->alias('o')
                    ->where($map)
                    ->where($map2)
                    ->select();
            }

            if(!empty($order_list)){
                foreach ($order_list as &$v){

                    $v['dates'] = $day;

                    $archvices = ArchivesModel::getOneStat($v['id'],'order_id','eq','',[$day_start,$day_end],$status);

                    $v = array_merge($v,$archvices);

                    //小计
                    $status_sum += $v['status_sum'];
                    $status_area_sum += $v['status_area_sum'];
                    //合计
                    $all_status_sum += $v['status_sum'];
                    $all_status_area_sum += $v['status_area_sum'];

                    $data_list[] = $v;
                }

                //小计
                $group_val = [
                    'id'    =>  '',
                    'area_sum'       =>  "小计",
                    'status_sum'           =>  $status_sum,
                    'status_area_sum'  =>  $status_area_sum,
                    'create_time'       =>  0,
                ];
                $data_list[] = $group_val;

                //重置
                $status_sum = 0;
                $status_area_sum = 0;

            }

        }
        if(!empty($data_list)){

            //合计
            $group_val = [
                'id'    =>  '',
                'area_sum'       =>  "合计",
                'status1'           =>  $all_status_sum,
                'status1_area_sum'  =>  $all_status_area_sum,
                'create_time'       =>  0,
            ];
            $data_list[] = $group_val;
        }

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                            
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        $give_status_search = GiveModel::$give_status_search;
        unset($give_status_search[0]);
        unset($give_status_search[2]);
        unset($give_status_search[4]);
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['select:2', 'status', '排期','',$status,$give_status_search],
                ['text:2', 'o.archives_sn', '档案号', 'like'],
                ['daterange:2', 'times', '日期','',"{$starttime} - {$endtime}"],
            ])
            ->addColumns([ // 批量添加列
                ['dates', '日期'],
                ['archives_sn', '档案号'],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum', '产品总量'],
                ['area_sum','总面积'],
                ['status_sum','日产量'],
                ['status_area_sum','日产面积'],
                ['number_ok_sum','总完成数量'],
                ['area_ok_sum','总完成面积'],
                ['number_on_sum','未完成数量'],
                ['area_on_sum','未完成面积'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('plan',['title' => '计划单','href' => url('mill/order/plan',['give_status'=>$status]),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '55%'], 'title' => ['计划单', 'font-size:24px;text-align: center;']])
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->addRightButton('deliverShow',['title' => '删除计划','href' => url('mill/order/planDel',['order_id'=>'__id__','archives_sn'=>'__archives_sn__','give_status'=>$status,'starttime'=>$starttime,'endtime'=>$endtime]),'class'=>'btn btn-primary disable-dch ajax-get confirm','icon'=>''])
            ->replaceRightButton(['id'=>['=','']],'')
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板

    }
    /**
     * 开料生产统计
     * @return mixed
     */
    public function schedulCutting()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        return $this->schedul(1);
    }
    /**
     * 喷涂生产统计
     * @return mixed
     */
    public function schedulSpray()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        return $this->schedul(3);
    }
    /**
     * 开料员工统计
     */
    public function userSpeed($archives_status=1)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $status_arr = [1=>'开料',2=>'钣金',3=>'喷涂',4=>'发货'];
        $title = '员工统计';
        if($archives_status)$title = $status_arr[$archives_status].$title;
        // 获取查询条件
        $map = $this->getMap();
        $map2 = [['g.status','>',0]];
        //默认日期：本月
        $starttime = strtotime(date('Y-m-01'));
        $endtime = strtotime(date('Y-m-d 23:59:59'));
        //默认扫码人
        $user_id = '';

        $starttime2 = date('Y-m-d',$starttime);
        $endtime2 = date('Y-m-d',$endtime);
        $title .= "{$starttime2}-{$endtime2}";

        $count_arr = [
            'id'                =>  '',
            'date_title'        =>  '合计',
            'number_sum'        =>  0,
            'area_sum'          =>  0,
            'starttime'         =>  $starttime2,
            'endtime'           =>  $endtime2,
        ];

        if(!empty($map)){
            $m_v_i = 0;
            foreach ($map as &$m_v){
                if (in_array('times',$m_v)){
                    $starttime = strtotime($m_v[2][0]);
                    $endtime = strtotime($m_v[2][1]);
                    unset($map[$m_v_i]);
                }
                elseif (in_array('user_id',$m_v)){
                    $user_id = $m_v[2];
                    unset($map[$m_v_i]);
                }

                $m_v_i++;
            }
        }
        //按月统计：时间差
        //$day_time = abs(date('Y',$endtime+1)-date('Y',$starttime)) * 12 + abs(date('m',$endtime+1)-date('m',$starttime));
        $day_cout = $day_time = abs(date('Y',$endtime+1)-date('Y',$starttime)) * 12 + abs(date('m',$endtime)-date('m',$starttime));

        //获取扫码人
        $user_where = [
            ['u.status','=',1],
            ['u.delete','=',1],
            ['u.group','=',5],
        ];
        $user_lists = UserModel::getList($user_where);

        //生产状态：0待生产，1开料，2钣金，3挂件喷涂，4发货
        if(empty($user_id)) $map2[] = ['g.status_flow','like',"%\\_{$archives_status}|%"];
        else {
            $map2[] = ['g.status_flow','like',"%\\_{$archives_status}|{$user_id}\\_%"];
            $user_where[] = ['u.id','=',$user_id];
        }

        $user_list = UserModel::getList($user_where,'u.nickname');
        unset($user_list[0]);
        unset($user_list[1]);

        while (0 <= $day_time) {

            //$new_date = date('Y-m-01', strtotime("-{$day_time} month",strtotime(date('Y-m-01',($endtime + 1)))));
            $new_date = date('Y-m-01', strtotime("-{$day_time} month",strtotime(date('Y-m-01',$endtime))));
            $end_date = date('Y-m-d H:i:s',strtotime("+1 month",strtotime($new_date))-1);
            if($day_cout == $day_time)$new_date = date('Y-m-d H:i:s',$starttime);
            if($day_time == 0)$end_date = date('Y-m-d H:i:s',$endtime);

            //条件
            $map_time = [["g.status{$archives_status}_time",'between time',"{$new_date},{$end_date}"]];

            $count_info = [
                'id'                =>  '',
                'date_title'        =>  '小计',
                'number_sum'        =>  0,
                'area_sum'          =>  0,
            ];

            //遍历扫码人
            foreach ($user_list as $uk=>$un){

                $map3 = [['g.status_flow','like',"%\\_{$archives_status}|{$uk}\\_%"]];

                $info = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field("COUNT(g.id) AS number_sum,SUM(a.one_area) AS area_sum")
                    ->leftJoin('mill_order_archives a','g.archives_id=a.id')
                    ->where($map)
                    ->where($map2)
                    ->where($map3)
                    ->where($map_time)
                    ->find();

                $info['id'] = $uk;
                $info['nickname'] = $un;
                $info['date_title'] = date('Y年m月',strtotime($new_date));

                //小计
                $count_info['number_sum'] += $info['number_sum'];
                $count_info['area_sum'] += $info['area_sum'];
                //合计
                $count_arr['number_sum'] += $info['number_sum'];
                $count_arr['area_sum'] += $info['area_sum'];

                $data_list[] = $info;
            }
            $data_list[] = $count_info;

            --$day_time;
        }
        $data_list[] = $count_arr;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['select:2', 'user_id', '扫码人', '=', '', $user_lists],
                ['daterange:2', 'times', '日期','',$starttime2.' - '.$endtime2],
            ])
            ->addColumns([ // 批量添加列
                ['date_title', '日期'],
                ['nickname', '扫码人'],
                ['number_sum','总数量(件)'],
                ['area_sum','总面积(M²)'],
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }

}
